package com.kang.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.alibaba.fastjson.JSON;
import com.kang.pojo.AjaxResult;
import com.kang.pojo.GeneralStorage;
import com.kang.pojo.GgeneralStoragePoJo;
import com.kang.pojo.IntemInformation;
import com.kang.pojo.Picking;
import com.kang.pojo.PickingItem;
import com.kang.pojo.PickingReturn;
import com.kang.pojo.PickingreturnIteminformation;
import com.kang.pojo.Warehouse;
import com.kang.service.IntemInformationService;
import com.kang.service.PickingReturnService;
import com.kang.service.PickingService;
import com.kang.service.PickingreturnIteminformationService;
import com.kang.service.UserService;
import com.kang.service.WarehouseService;
import com.kang.until.StoragePDF;
import com.vonechina.entity.page.GeneralStoragePage;
import com.vonechina.entity.page.PickingPage;
import com.vonechina.entity.page.PickingReturnPage;

/**
 * 领料归还
 * 
 * @author ysq
 *
 */
@Controller
@RequestMapping("pickingReturnContrlooer")
@SessionAttributes({ "pickingReturnPage" })
public class PickingReturnContrlooer extends com.kang.controller.Controller {

	/**
	 * 用户管理服务
	 */
	@Resource
	private UserService users;
	/**
	 * 物品服务
	 */
	@Resource
	private IntemInformationService iifs;
	/**
	 * 仓库服务
	 */
	@Resource
	private WarehouseService warehouseService;
	/**
	 * 领料归还服务
	 */
	@Resource
	private PickingReturnService pickingReturnService;
	/**
	 * 领料归还_物品服务
	 */
	@Resource
	private PickingreturnIteminformationService pickingreturnIteminformationService;
	/**
	 * 领料出库
	 */
	@Resource
	private PickingService pickingService;

	/**
	 * 根据pickingreturnID删除pickingreturn
	 * 
	 * @param pickingreturnID
	 * @return
	 */
	@RequestMapping("deletePickingreturn")
	@ResponseBody
	public String deletePickingreturn(Integer pickingreturnID) {
		AjaxResult result = new AjaxResult();
		// 根据pickingreturnID删除pickingreturn
		int a = pickingReturnService.deletePickingreturn(pickingreturnID);
		// 根据pickingreturnID删除所有pickingreturn_iteminformation信息
		int b = pickingreturnIteminformationService
				.delPickingreturnIteminformation(pickingreturnID);

		if (a > 0 && b > 0) {
			result.setResult("success");
		} else {
			result.setResult("fail");
		}

		return JSON.toJSONString(result);
	}

	/**
	 * 去到查看领料归还详情
	 * 
	 * @param model
	 * @param pickingreturnID
	 * @return
	 */
	@RequestMapping("toDetailspickingReturn")
	public String toDetailspickingReturn(Model model, Integer pickingreturnID) {
		// 根据pickingreturnID查询领料归还
		PickingReturn pickingReturn = pickingReturnService
				.selectPickingReturnByPickingreturnID(pickingreturnID);
		model.addAttribute("pickingReturn", pickingReturn);

		// 根据pickingreturnID查询领料归还_物品信息
		List<PickingreturnIteminformation> list1 = pickingreturnIteminformationService
				.selectPickingreturnIteminformationByPickingreturnID(pickingreturnID);

		model.addAttribute("list2", list1);

		model.addAttribute("createPerson",
				users.getUserById(pickingReturn.getCreatePersonID() + "")
						.get(0));// 根据用户id查询出用户信息和关联的角色信息
		model.addAttribute("buyer",
				users.getUserById(pickingReturn.getBuyerID() + "").get(0));// 根据用户id查询出用户信息和关联的角色信息

		model.addAttribute("lastPerson",
				users.getUserById(pickingReturn.getLastPersonID() + "").get(0));// 根据用户id查询出用户信息和关联的角色信息

		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());// 查询仓库
		return "storage/pickingReturn/detailsPickingReturn";
	}

	/**
	 * 去到修改领料归还
	 * 
	 * @param session
	 * @param model
	 * @param pickingreturnID
	 * @return
	 */
	@RequestMapping("toUpdate")
	public String updateWarehouseorder(HttpSession session, Model model,
			Integer pickingreturnID) {
		initRight(session);
		if (checkRight("编辑全部领料归还") != SUCCESS) {
			return "basic/noRight";
		}

		// 根据pickingreturnID查询领料归还
		PickingReturn pickingReturn = pickingReturnService
				.selectPickingReturnByPickingreturnID(pickingreturnID);
		model.addAttribute("pickingReturn", pickingReturn);

		// 根据pickingreturnID查询领料归还_物品信息
		List<PickingreturnIteminformation> list1 = pickingreturnIteminformationService
				.selectPickingreturnIteminformationByPickingreturnID(pickingreturnID);

		model.addAttribute("list2", list1);

		model.addAttribute("createPerson",
				users.getUserById(pickingReturn.getCreatePersonID() + "")
						.get(0));// 根据用户id查询出用户信息和关联的角色信息
		model.addAttribute("buyer",
				users.getUserById(pickingReturn.getBuyerID() + "").get(0));// 根据用户id查询出用户信息和关联的角色信息

		model.addAttribute("lastPerson",
				users.getUserById(pickingReturn.getLastPersonID() + "").get(0));// 根据用户id查询出用户信息和关联的角色信息
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());// 查询仓库

		return "storage/pickingReturn/updatePickingReturn";
	}

	/**
	 * 修改领料归还
	 * 
	 * @param pickingReturn
	 * @param itemIds
	 * @param itemNumber
	 * @param id
	 * @return
	 */
	@RequestMapping("update")
	@ResponseBody
	public String updateWarehouseorder(PickingReturn pickingReturn,
			Integer[] itemIds, Integer[] itemNumber, Integer[] id,
			Integer[] item_detailId) {
		AjaxResult result = new AjaxResult();
		// 修改领料归还信息
		pickingReturnService.updatePickingReturn(pickingReturn);
		// 根据pickingreturnID删除所有pickingreturn_iteminformation信息
		pickingreturnIteminformationService
				.delPickingreturnIteminformation(pickingReturn
						.getPickingreturnID());

		for (int i = 0; i < itemIds.length; i++) {
			// 领料归还——物品
			PickingreturnIteminformation pickingreturnIteminformation = new PickingreturnIteminformation();
			pickingreturnIteminformation.setPickingreturnID(pickingReturn
					.getPickingreturnID());
			pickingreturnIteminformation.setItemInformationID(itemIds[i]);
			pickingreturnIteminformation.setNumber(itemNumber[i]);
			pickingreturnIteminformation.setSourceID(id[i]);
			pickingreturnIteminformation.setStatus(pickingReturn.getStatus());
			// 保存领料归还——物品
			pickingreturnIteminformationService
					.addPickingreturnIteminformation(pickingreturnIteminformation);

			// 如果是提交状态那就提交以及更改库存

			if (pickingReturn.getStatus().equals(1)) {
				// 物品表
				IntemInformation i2 = new IntemInformation();
				i2.setCurrentstock(itemNumber[i]);
				i2.setInteminformationid(itemIds[i]);
				iifs.updateIntemInformationCurrentStock(i2);// 修改库存

				// 根据id修改item_detail的number数量（归还后加上数量）
				pickingreturnIteminformationService
						.updateItem_detailNumberById(item_detailId[i],
								itemNumber[i]);

				// 修改领料出库——物品 修改领料归还数量
				PickingItem pickingItem = new PickingItem();
				pickingItem.setId(id[i]);
				pickingItem.setPickingreturnNumber(itemNumber[i]);
				pickingService.updatePickingIteminformation(pickingItem);

			}
		}

		result.setResult("success");
		return JSON.toJSONString(result);
	}

	/**
	 * 根据根据pickingID查询领料出库单里面的物品
	 * 
	 * @param pickingID
	 * @return
	 */
	@RequestMapping("listAddItem2")
	@ResponseBody
	public String listAddItem2(Integer pickingID) {
		// 根据pickingID查询领料出库单
		Picking picking1 = pickingReturnService
				.selectPickingByPickingID(pickingID);

		// 查询领料出库单下的物品
		List<PickingItem> list1 = pickingReturnService
				.selectPickingItemByPickingID(pickingID);

		List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>();

		if (list1 != null) {
			int list1Sum = list1.size();
			for (int i = 0; i < list1Sum; i++) {
				Map<String, Object> map1 = new HashMap<String, Object>();
				map1.put("picking1", picking1);
				map1.put("PickingItem", list1.get(i));
				list2.add(map1);
			}
		}
		return JSON.toJSONString(list2);
	}

	/**
	 * 添加领料归还-获取领料出库单
	 * 
	 * @param pickingPage
	 * @return
	 */
	@RequestMapping("listAddItem")
	@ResponseBody
	public String listAddItem(PickingPage pickingPage) {
		pickingPage.setPageSize(10);// 设置每页显示几条
		List<Picking> pickinglist1 = pickingReturnService
				.selectPickingList(pickingPage);// 查询数据
		AjaxResult result = new AjaxResult();
		result.setRows(pickinglist1);
		result.setTotal(pickingPage.getRows());
		return JSON.toJSONString(result);
	}

	/**
	 * 去到添加领料归还
	 * 
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping("toAdd")
	public String addGeneralStorage(HttpSession session, Model model) {
		initRight(session);
		if (checkRight("新增领料归还") != SUCCESS) {
			return "basic/noRight";
		}
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());// 查询可用仓库
		return "storage/pickingReturn/addPickingReturn";
	}

	/**
	 * 添加领料归还
	 * 
	 * @param pickingReturn
	 * @param itemIds
	 * @param itemNumber
	 * @param id
	 * @return
	 */
	@RequestMapping("add")
	@ResponseBody
	public String addWarehouseOrders(PickingReturn pickingReturn,
			Integer[] itemIds, Integer[] itemNumber, Integer[] id,
			Integer[] item_detailId) {
		AjaxResult result = new AjaxResult();

		// 生成领料归还单号
		pickingReturn.setPickingreturnNumber(pickingReturnService
				.generatePickingreturnNumber());
		// 添加领料归还
		pickingReturnService.addPickingReturn(pickingReturn);

		if (pickingReturn.getPickingreturnID() == null
				|| pickingReturn.getPickingreturnID() <= 0) {
			return JSON.toJSONString(result);
		}

		for (int i = 0; i < itemIds.length; i++) {
			// 领料归还——物品
			PickingreturnIteminformation pickingreturnIteminformation = new PickingreturnIteminformation();
			pickingreturnIteminformation.setPickingreturnID(pickingReturn
					.getPickingreturnID());
			pickingreturnIteminformation.setItemInformationID(itemIds[i]);
			pickingreturnIteminformation.setNumber(itemNumber[i]);
			pickingreturnIteminformation.setSourceID(id[i]);
			pickingreturnIteminformation.setStatus(pickingReturn.getStatus());
			// 保存领料归还——物品
			pickingreturnIteminformationService
					.addPickingreturnIteminformation(pickingreturnIteminformation);

			// 如果是提交状态那就提交以及更改库存

			if (pickingReturn.getStatus().equals(1)) {
				// 物品表
				IntemInformation i2 = new IntemInformation();
				i2.setCurrentstock(itemNumber[i]);
				i2.setInteminformationid(itemIds[i]);
				iifs.updateIntemInformationCurrentStock(i2);// 修改库存

				// 根据id修改item_detail的number数量（归还后加上数量）
				pickingreturnIteminformationService
						.updateItem_detailNumberById(item_detailId[i],
								itemNumber[i]);

				// 修改领料出库——物品 修改领料归还数量
				PickingItem pickingItem = new PickingItem();
				pickingItem.setId(id[i]);
				pickingItem.setPickingreturnNumber(itemNumber[i]);
				pickingService.updatePickingIteminformation(pickingItem);

			}
		}

		result.setResult("success");
		return JSON.toJSONString(result);
	}

	/**
	 * 查询领料归还
	 * 
	 * @param session
	 * @param model
	 * @param pickingReturnPage
	 * @return
	 */
	@RequestMapping("selectByWhere")
	public String PurchaseorderSelectByWhere(HttpSession session, Model model,
			PickingReturnPage pickingReturnPage) {
		initRight(session);
		if (checkRight("查看领料归还") != SUCCESS
				&& checkRight("查看全部领料归还") != SUCCESS) {
			return "basic/noRight";
		}
		if (checkRight("查看全部领料归还") == SUCCESS) {
			pickingReturnPage.setCreatePersonID(null);
		} else {
			pickingReturnPage.setCreatePersonID(userID + "");
		}

		List<PickingReturn> pickingReturnList = pickingReturnService
				.selectByWheres(pickingReturnPage);// 查询领料归还
		model.addAttribute("pickingReturnList", pickingReturnList);

		List<Warehouse> wm = warehouseService.listAllWarehouse();// 仓库
		model.addAttribute("wm", wm);

		pickingReturnPage
				.setPageUrl("pickingReturnContrlooer/selectByWhere.do");
		model.addAttribute("page", pickingReturnPage);
		return "storage/pickingReturn/listPickingReturn";
	}
	
	
	/**
	 * 导出领用归还PDF文件
	 * 
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("downloads")
	public void downloadPDF(HttpServletResponse response, PickingReturnPage pickingReturnPage)
			throws Exception {
		//System.out.println("=============导出采购入库PDF文件===============");
		List<PickingReturn> pkList = pickingReturnService.selectByWheres(pickingReturnPage);
		//此方法为直接下载文件
		//File file = WarehouseOrderPDF.buildWarehouseOrderPDF(warehouseOrder, pOrderItem);
		File file = StoragePDF.PickingReturnPDF(pkList);
		if (file.isFile() && file.exists()) {
			try {
				 InputStream fis = new BufferedInputStream(new FileInputStream(file));
				    byte[] buffer = new byte[fis.available()];
				    fis.read(buffer);
				    fis.close();
				    response.reset();
				    //乱码处理
				    //先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
				    response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
				    response.addHeader("Content-Length", "" + file.length());
				    OutputStream os = new BufferedOutputStream(response.getOutputStream());
				    response.setContentType("application/octet-stream");
				    os.write(buffer);//输出文件
				    os.flush();
				    os.close();//关闭流，释放资源！
			} catch (Exception e) {
				e.printStackTrace();
			}
			file.delete();
		}
	}
	
	
}
